import {
  Box, Button, Dialog, DialogActions, DialogContent,
  DialogTitle, Grid, TextField, Typography
} from "@mui/material"
import { evaluate } from 'mathjs'
import { useEffect, useRef, useState } from "react"
import FormulaButtons from "./FormulaButtons"

interface IProps {
  name: string,
  value: any,
  open: boolean,
  onOk: (value: any) => void,
  onClose: () => void
}
export default function Forluma({ name, value: initValue, onOk, open, onClose }: IProps) {
  const [value, setValue] = useState(initValue)
  const inputRef = useRef(null)
  const [error, setError] = useState({ error: false, message: '' })

  useEffect(() => setValue(initValue), [initValue])
  const handleChange = (v: string) => {
    console.log(inputRef.current.selectionStart)
    setValue(v)
    try {
      evaluate(v, { x: 1, y: 2, z: 3, t: 4 })
    } catch (e: any) {
      setError({ error: true, message: e.message })
      return
    }
    setError({ error: false, message: '' })
  }
  return (
    <Dialog open={open}
      onClose={onClose}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description">
      <DialogTitle id="alert-dialog-title">
        {'设置值'}
      </DialogTitle>
      <DialogContent>
        <Box sx={{ flexGrow: 1 }}>
          <Grid container sx={{ mb: 2 }} spacing={2}>
            <Grid item xs={6}>
              <TextField error={error.error} id={name} autoFocus
                inputRef={inputRef} value={value} variant="standard"
                onChange={e => handleChange(e.target.value)} />
            </Grid>
            <Grid item xs={6}>
              <Typography color='error'>{error.message}</Typography>
            </Grid>
          </Grid>
          <FormulaButtons onClick={v => {
            if (value === '0') {
              handleChange(v)
            } else {
              handleChange(value + v)
            }
          }} />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button variant="contained" disabled={error.error || value.length === 0}
          onClick={() => onOk(value)}>
          确定
        </Button>
        <Button variant="outlined" onClick={onClose}>取消</Button>
      </DialogActions>
    </Dialog>
  )
}